package com.gel.codegeneration.core.parser;

import com.gel.codegeneration.ai.model.entity.HtmlCodeResult;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @BelongsProject: code-generation-platform
 * @BelongsPackage: com.gel.codegeneration.core.parser
 * @Author: gel
 * @CreateTime: 2025-08-22  15:35
 * @Description: TODO Html文件代码解析器
 * @Version: 1.0
 */
public class HtmlCodeParser implements CodeParser<HtmlCodeResult>{
    private static final Pattern HTML_CODE_PATTERN = Pattern.compile("```html\\s*\\n([\\s\\S]*?)```", Pattern.CASE_INSENSITIVE);

    //解析代码
    @Override
    public HtmlCodeResult parseCode(String codeContent) {
        HtmlCodeResult result = new HtmlCodeResult();
        String htmlCode = extractCodeByPattern(codeContent, HTML_CODE_PATTERN);
        //提取html代码块
        if(htmlCode != null&&!htmlCode.trim().isEmpty()){
            result.setHtmlCode(htmlCode);
        }else {
            //没有提取到代码块，将整个内容作为HTML
            result.setHtmlCode(codeContent);
        }

        return result;

    }

    public String extractCodeByPattern(String content, Pattern pattern){
        Matcher matcher = pattern.matcher(content);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return null;
    }


}
